package com.zone.trigger.job;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.zone.domain.task.model.entity.TaskEntity;
import com.zone.domain.task.service.ITaskService;
import com.zone.types.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: zongzi
 * @description: 任务扫描
 * @date: 2025/2/24
 */
@Slf4j
@Component
public class TaskJob {
    @Autowired
    private ITaskService taskService;

    //    @Scheduled(cron = "0 0/5 * * * ? ")   //每5分钟执行一次
    @XxlJob("SendMessageTaskJob")
    public void execute() {
        List<TaskEntity> taskEntities = taskService.queryNoSendTaskList();
        if (CollectionUtils.isEmpty(taskEntities)) {
            log.info("任务扫描，未查询到任务信息");
            return;
        }
        for (TaskEntity taskEntity : taskEntities) {
            try {
                taskService.sendMessage(taskEntity);
                taskService.updateCompleteByUserIdAndMessageId(taskEntity.getUserId(), taskEntity.getMessageId());
            } catch (Exception e) {
                log.info("定时器执行任务发送失败 task ={}", taskEntity, e);
                taskService.updateFailByUserIdAndMessageId(taskEntity.getUserId(), taskEntity.getMessageId());
            }
        }
    }
}
